<template>
  <div class="rh-select"
       @click="click">
    <rh-input type='text'
              :placeholder='placeholder'
              v-model='text'
              readonly
              ref="input"></rh-input>
    <ul ref="ul">
      <li v-for='item in options'
          :key='item.value'
          @click="select([item.label,item.value])">{{ item.label }}</li>
    </ul>
  </div>
</template>

<script>
import RhInput from '@/components/basic/rh-input'
export default {
  data () {
    return {
      active: false,
      text: ''
    }
  },
  watch: {
    value () {
      this.options.map((item, i) => {
        if (item.value == this.value) {
          this.text = item.label;
          this.$refs.ul.children[i].className = 'select';
          return;
        }
      })
    }
  },
  props: {
    value: {
      default: ''
    },
    placeholder: {
      default: '请选择'
    },
    options: {
      type: Array
    }
  },
  components: {
    RhInput
  },
  methods: {
    click () {
      if (!this.active) {
        this.$refs.ul.classList.add('active');
      } else {
        this.$refs.ul.classList.remove('active');
      }
      this.active = !this.active;
    },
    select ([label, value]) {
      this.text = label;
      this.$emit('input', value);
      this.$refs.input.$refs['rh-input'].value = label;
      // 修改被选中的属性
      Array.from(this.$refs.ul.children).map(item => {
        if (item.innerText == label) {
          item.className = 'select';
        } else {
          item.className = '';
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.rh-select {
  width: 217px;
  height: 40px;

  ul {
    position: relative;
    width: calc(100% - 2px);
    padding: 6px 0;
    border-radius: 2px;
    box-shadow: 0 0 3px #909399;
    margin-top: 10px;
    display: none;
    background-color: #fff;
    z-index: 99;

    li {
      width: 100%;
      height: 34px;
      line-height: 34px;
      text-align: left;
      padding: 0 20px;
      color: #606266;
      cursor: pointer;
      box-sizing: border-box;
      font-size: 14px;
    }
    li:hover {
      background-color: #f2f6fc;
    }
    .select {
      background-color: #f2f6fc;
      color: #f10;
    }
  }
  .active {
    display: block;
  }
}
</style>